/*
 * Searcher.java
 *
 * Created on August 1, 2007, 9:26 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */
package com.afaker.rss.search;

import com.afaker.rss.context.ResourceContext;
import java.io.IOException;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryParser.MultiFieldQueryParser;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.Hits;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;

/**
 *
 * @author bruce
 */
public class Searcher {

    private static final String INDEX_DIR =
            ResourceContext.getResourceContext().getProperty("index.dir");
    IndexSearcher search = null;
    IndexReader reader = null;

    /** Creates a new instance of Searcher */
    public Searcher() {
    }

    public Hits search(String keyword) {
        try {
            reader = IndexReader.open(INDEX_DIR);
        } catch (CorruptIndexException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        search = new IndexSearcher(reader);

        QueryParser parser = new MultiFieldQueryParser(
                new String[]{Indexer.SUMMARY_FIELD, Indexer.CATEGORY_FIELD},
                new StandardAnalyzer());
        Query query = null;
        try {
            query = parser.parse(keyword);
        } catch (ParseException ex) {
            ex.printStackTrace();
        }
        Hits hit = null;
        try {
            hit = search.search(query);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        try {
            search.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return hit;
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Searcher s = new Searcher();
        Hits hits = s.search("dfdf");
        System.out.println(hits.length());
    }
}
